package com.dayangxiaoen.pms.interceptor;

import com.alibaba.fastjson.JSON;
import com.dayangxiaoen.pms.enums.StatusCode;
import com.dayangxiaoen.pms.po.User;
import com.dayangxiaoen.pms.service.UserService;
import com.dayangxiaoen.pms.utils.UserThreadUtils;
import com.dayangxiaoen.pms.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author dayangxiaoen
 */

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // TODO 1. 获取请求头中的相关 token
        String token = request.getHeader("Authorization");


        // TODO 2. 判断 token是否为空，如果为空 未登录
        if (StringUtils.isBlank(token)){
            Result result = Result.fail(StatusCode.NO_LOGIN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }

        // TODO 3. 如果token 不为空，登录验证 loginService checkToken
        User user = userService.checkToken(token);
        if (user == null){
            Result result = Result.fail(StatusCode.NO_LOGIN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }


        // TODO 4.登录验证成功，放行
        // 为了在今后的 controller 或者其它操作中直接获得 该用户 这将该用户 放在本地线程中
        UserThreadUtils.put(user);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // TODO 在本次请求结束之后 直接删除相关线程中数据
        UserThreadUtils.remove();
    }
}

